package com.wlbx.agent.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.adapter.ProductAdapter;
import com.wlbx.agent.base.BaseFragment;
import com.wlbx.agent.bean.ProductListBean;
import com.wlbx.agent.event.UpdateProductListEvent;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.ui.activity.MainActivity;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 产品列表
 */
public class ProductListFragment extends BaseFragment {
    public static final String EXTRA_TEXT = "extra_text";

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    private ProductAdapter mAdapter;
    private static final int PAGE_SIZE = 10;
    //需要一个外部传入的type变量,即本ProductListFragment可能显示的内容不同，比如意外险、寿险等
    private String productSubType="";
    private String productName="";
    private String suitableGroup;
    private String isOnline;
    private String partnerId ;
    List<ProductListBean.DataDTO.ListDTO> data;
    static class PageInfo {
        int page = 1;

        void nextPage() {
            page++;
        }

        void reset() {
            page = 1;
        }

        boolean isFirstPage() {
            return page == 1;
        }
    }

    private PageInfo pageInfo = new PageInfo();

    @Override
    protected int getInflateViewId() {
        return R.layout.fragment_product_list;
    }


    public static ProductListFragment getInstance(){
        return new ProductListFragment();
    }


    @Override
    public void initData() {
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }

        initAdapter();
        getProductList(pageInfo.page,productSubType,isOnline,partnerId,suitableGroup,productName);

    }



    public void getProductList(int page, String productSubType, String isOnline, String partnerId , String suitableGroup, String productName) {
        if (swipeLayout!=null){
            swipeLayout.setRefreshing(true);
        }
        final Map<String, Object> map = new HashMap<>();
        map.put("curPage",String.valueOf(page));
        map.put("length", String.valueOf(PAGE_SIZE));
        if (!TextUtils.isEmpty(isOnline)){
            map.put("isOnline",isOnline);//产品子类型
        }
        if (!TextUtils.isEmpty(partnerId)){
            map.put("partnerId",partnerId);//合作机构
        }
        if (!TextUtils.isEmpty(productSubType)){
            map.put("productSubType",productSubType);//产品子类型
        }
        if (!TextUtils.isEmpty(suitableGroup)){
            map.put("suitableGroup",suitableGroup);//产品子类型
        }
        if (!TextUtils.isEmpty(productName)){
            map.put("productName",productName);//产品子类型
        }
            Logger.i("传参------"+JSON.toJSONString(map));
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getProductList(map)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i( response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg = jsonObject.getString("msg");
                        if ("1000".equals(rCode)) {
                            ProductListBean bean=JSON.parseObject(response,ProductListBean.class);
                            if (swipeLayout!=null){
                                swipeLayout.setRefreshing(false);
                            }

                            mAdapter.getLoadMoreModule().setEnableLoadMore(true);
                             data = bean.getData().getList();

                            if (data.size()<=0||data==null){
                                mAdapter.setEmptyView(R.layout.no_data_view);
                            }

                        if (pageInfo.isFirstPage()) {
                            mAdapter.setList(data);
                        } else {
                            mAdapter.addData(data);
                        }

                        if (data.size() < PAGE_SIZE) {
                            mAdapter.getLoadMoreModule().loadMoreEnd();
                        } else {
                            mAdapter.getLoadMoreModule().loadMoreComplete();
                        }

                        pageInfo.nextPage();
                        }else{
                            Toast.makeText(getActivity(),rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }


    private void initAdapter() {
        mAdapter = new ProductAdapter(mActivity);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setAdapter(mAdapter);
        mAdapter.setAnimationEnable(true);

        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                productName=Constant.PRODUCT_NAME;
                pageInfo.reset();
                getProductList(pageInfo.page,productSubType,isOnline,partnerId,suitableGroup,productName);
                mAdapter.getLoadMoreModule().setEnableLoadMore(false);
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                if (AccountManager.hasUserLogin()){
                    ProductListBean.DataDTO.ListDTO bean = mAdapter.getData().get(position);
                    Logger.i(JSON.toJSONString(bean));
                    IntentUtil.goProductDetailActivity(bean,getActivity());

                }else {
                    IntentUtil.goLoginActivity(getActivity());
                }


            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                ProductListBean.DataDTO.ListDTO bean = mAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.iv_logo_url:
                        if (AccountManager.hasUserLogin()){
                            Logger.i(JSON.toJSONString(bean));
                            IntentUtil.goProductDetailActivity(bean,getActivity());

                        }else {
                            IntentUtil.goLoginActivity(getActivity());
                        }
                        break;
                    default:
                        break;
                }
            }
        });


        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getProductList(pageInfo.page,productSubType,isOnline,partnerId,suitableGroup,productName);
            }
        });
    }

    @Override
    public void initEvent() {


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void refreshList(UpdateProductListEvent updateProductListEvent) {
        isOnline = updateProductListEvent.getIsOnline();
        partnerId=updateProductListEvent.getPartnerId();
        productName=updateProductListEvent.getProductName();
        productSubType=updateProductListEvent.getProductSubType();
        Logger.i("isOnline---"+isOnline+"\npartnerId---"+partnerId+"\nproductName---"+productName+"\nproductSubType---"+productSubType);


        if (data!=null||data.size()>0){
            data.clear();
        }
        pageInfo.reset();
        getProductList(pageInfo.page,productSubType,isOnline,partnerId,suitableGroup,productName);
    }


}
